package android.material.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.material.util.ActionIcon;
import android.material.util.Util;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import hd.util.ScreenHelper;

/**
 * TitleBar上的按钮
 * <p/>
 * Created by Haidy on 15/1/3.
 */
public class ActionView extends View {

    private static final short ANIMATION_DURATION = 200;
    public static final int MORE = 0;
    private final Paint paint;
    private final Paint textPaint;
    private final int textHeight;
    private boolean pressed = false;//当前是否按下
    private boolean animStop = true;//动画是否停止
    private int circleRadius = 0;//当前圆的半径
    private long animStartTime;
    private Point point = new Point();
    private final int ANIM_RATE = ScreenHelper.dp2px(getContext(), 40); //动画的速率
    private final int ANIM_ACC_RATE = ScreenHelper.dp2px(getContext(), 1);//失去焦点加速的速率
    private int currentAnimRate = 0;//当前速率
    private int currentAlpha = 0;
    private int currentBackgroundAlpha = 0;
    private Rect rect;
    private int backgroundColor;
    private String actionName;
    private Bitmap bmpIcon;
    private int r;
    private int type;

    public ActionView(Context context) {
        this(context, null);
    }

    public ActionView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ActionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        paint = new Paint();
        paint.setColor(Color.rgb(0, 0, 0));
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(ScreenHelper.sp2px(getContext(), 18));
        textPaint.setTextAlign(Paint.Align.CENTER);
        textHeight = ScreenHelper.getFontHeight(18);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int height = getContext().getResources().getDimensionPixelSize(R.dimen.titleBarHeight);
        r = (int) (Math.ceil(height * Math.sqrt(2)) / 2);
        int width = MeasureSpec.getSize(height / 2 + r);
        setMeasuredDimension(width, height);
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        rect = new Rect(0, 0, getWidth(), getHeight());
        super.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                pressed = true;//按下
                point.x = (int) event.getX();
                point.y = (int) event.getY();//记录按下的位置
                animStop = false;
                circleRadius = 0;
                animStartTime = System.currentTimeMillis();//记录开始的时间
                currentAnimRate = ANIM_RATE;
                currentBackgroundAlpha = 0;
                paint.setAlpha(currentAlpha = 0x20);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                Point p = new Point((int) event.getX(), (int) event.getY());
                if (!Util.inRect(p, rect)) {
                    actionUp();
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL://取消和抬起是一个效果
                actionUp();
                break;
        }
        return true;
    }

    private void actionUp() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                pressed = false;//抬起
                invalidate();//快速的消失波纹
            }
        }, 100);
    }


    /**
     * 设置背景颜色
     *
     * @param color 颜色
     */
    @Override
    public void setBackgroundColor(int color) {
        super.setBackgroundColor(color);
        this.backgroundColor = color;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(backgroundColor);
        int sc = canvas.saveLayer(0, 0, getWidth(), getHeight(), null,
                Canvas.MATRIX_SAVE_FLAG |
                        Canvas.CLIP_SAVE_FLAG |
                        Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
                        Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
                        Canvas.CLIP_TO_LAYER_SAVE_FLAG);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
        if (pressed) {
            if (Util.circleInRect(circleRadius, point, rect)) {
                if (currentBackgroundAlpha < 0x20)
                    currentBackgroundAlpha++;
                paint.setColor(Color.argb(currentBackgroundAlpha, 0, 0, 0));
                canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
                long time = System.currentTimeMillis() - animStartTime;
                circleRadius = Math.round(time * ANIM_RATE / ANIMATION_DURATION);
                paint.setColor(Color.argb(currentAlpha, 0, 0, 0));
                canvas.drawCircle(point.x, point.y, circleRadius, paint);
                invalidate();
            } else {//画出最后一帧结束
                paint.setColor(Color.argb(currentBackgroundAlpha, 0, 0, 0));
                canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
                paint.setColor(Color.argb(currentAlpha, 0, 0, 0));
                canvas.drawCircle(point.x, point.y, circleRadius, paint);
                animStop = true;
            }
        } else {
            if (animStop) {
                if (currentAlpha > 0 || currentBackgroundAlpha > 0) {
                    currentAlpha -= 2;//透明度变化的速率
                    currentAlpha = currentAlpha < 0 ? 0 : currentAlpha;
                    paint.setColor(Color.argb(currentAlpha, 0, 0, 0));
                    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
                    --currentBackgroundAlpha;
                    currentBackgroundAlpha = currentBackgroundAlpha < 0 ? 0 : currentBackgroundAlpha;
                    paint.setColor(Color.argb(currentBackgroundAlpha, 0, 0, 0));
                    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
                    invalidate();
                }
            } else {//动画还没消失，就快速扩大到最大半径
                if (Util.circleInRect(circleRadius, point, rect)) {
                    long time = System.currentTimeMillis() - animStartTime;
                    currentAnimRate += ANIM_ACC_RATE;//松手时加快的速率，越大扩散速度越快
                    circleRadius = Math.round(time * currentAnimRate / ANIMATION_DURATION);
                    paint.setColor(Color.argb(currentBackgroundAlpha, 0, 0, 0));
                    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

                    paint.setColor(Color.argb(currentAlpha, 0, 0, 0));
                    canvas.drawCircle(point.x, point.y, circleRadius, paint);
                    invalidate();
                } else {//画出最后一帧结束
                    paint.setColor(Color.argb(currentBackgroundAlpha, 0, 0, 0));
                    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

                    paint.setColor(Color.argb(currentAlpha, 0, 0, 0));
                    canvas.drawCircle(point.x, point.y, circleRadius, paint);
                    animStop = true;
                    invalidate();
                }
            }
        }
        paint.setXfermode(null);
        canvas.restoreToCount(sc);
        if (bmpIcon != null && !bmpIcon.isRecycled()) {
            canvas.drawBitmap(bmpIcon, (getWidth() - bmpIcon.getWidth()) / 2, (getHeight() - bmpIcon.getHeight()) / 2, null);
        } else if (actionName != null) {
            int height = (getHeight() + textHeight) / 2;
            canvas.drawText(actionName, getWidth() / 2, height, textPaint);
        } else {
            ActionIcon.drawType(getContext(), type, canvas, getWidth(), getHeight());
        }
        super.onDraw(canvas);
    }

    /**
     * 设置名称
     *
     * @param str actionName
     */
    public void setActionName(String str) {
        this.actionName = str;
    }

    /**
     * 设置图标
     *
     * @param icon 图标
     */
    public void setActionIcon(Drawable icon) {
        if (bmpIcon != null && !bmpIcon.isRecycled()) {
            bmpIcon.recycle();
            bmpIcon = null;
        }
        this.bmpIcon = ((BitmapDrawable) icon).getBitmap();
    }

    /**
     * 设置导航的类型
     *
     * @param type type
     */
    public void setType(int type) {
        this.type = type;
    }
}
